﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using WinnerCMS.Data;
using WinnerCMS.Model;
using WinnerCMS.Common;
using System.Data.Entity;
namespace WinnerCMS.Data
{
    /// <summary>
    /// 收货地址
    /// </summary>
    public class UserAddressDal
    {
        /// <summary>
        /// 添加用户收货地址
        /// </summary>
        /// <param name="model"></param>
        public void Add(UserAddress model)
        {
            using (Entities db = new Entities())
            {
                db.UserAddres.Add(model);
                db.SaveChangesAsync().Wait();

                if (model.IsDefault)
                {
                    db.Database.ExecuteSqlCommand("UPDATE CMS_UserAddresses set IsDefault=0 where UserID={0}", model.UserId);

                    db.Database.ExecuteSqlCommand("UPDATE CMS_UserAddresses set IsDefault=1 where Id={0}", model.Id);

                    
                }
            }

        }

        public void Delete(int Id)
        {
            using (Entities db = new Entities())
            {
                var q = db.UserAddres.Where(x => x.Id == Id).First();
                db.UserAddres.Remove(q);
                db.SaveChangesAsync().Wait();
            }
        }

        public void Edit(UserAddress model)
        {
            using (Entities db = new Entities())
            {
                db.UserAddres.Attach(model);
                db.Entry(model).State = EntityState.Modified;
                db.SaveChangesAsync().Wait();

                if (model.IsDefault)
                {
                    db.Database.ExecuteSqlCommand("UPDATE CMS_UserAddresses set IsDefault=0 where UserID={0}", model.UserId);

                    db.Database.ExecuteSqlCommand("UPDATE CMS_UserAddresses set IsDefault=1 where Id={0}", model.Id);
                }
            }
        }

        public UserAddress SelectByID(int Id)
        {
            using (Entities db = new Entities())
            {
                return db.UserAddres.First(x => x.Id == Id);
            }
        }

        public IList<UserAddress> SelectByUserName(string userName)
        {
            using (Entities db = new Entities())
            {
                return db.UserAddres.Where(x => x.User.UserName == userName).ToList();
            }
        }
    }
}
